package BC;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;

import java.io.*;

import java.security.NoSuchProviderException;
import java.security.Security;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;

public class PemToDer {
    public  static X509Certificate getPemCert(String path) throws IOException, CertificateException, NoSuchProviderException {
        //加载BC
        Security.addProvider( new BouncyCastleProvider() );

        PemReader pemReader = new PemReader( new FileReader(path) );
        PemObject pemObject = pemReader.readPemObject();
        byte cert[] = pemObject.getContent();
        //输出X509格式证书
        InputStream inStream = new ByteArrayInputStream(cert);
        //获取工厂实例
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
        Certificate certificate = certificateFactory.generateCertificate(inStream);//用文件流读入证书
        X509Certificate x509Certificate = (X509Certificate)certificate;
        return x509Certificate;
    }

    public static void writeDerCert(String path, X509Certificate x509Certificate) throws IOException, CertificateEncodingException {
        //转换DER证书
        byte[] cert = x509Certificate.getEncoded();
        File file=new File(path);
        if(!file.exists()){
            file.createNewFile();
        }
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(cert);
        fos.close();
        System.out.println("Successful!");
    }
    public static void main(String[] args) throws Exception {
        String pathSrc = "lzc_cert_demo.pem";
        String pathDst = "lzc_cert_demo.der";
        String s = pathSrc.substring(pathSrc.length() - 3);
        /*if (!((s.equals("pem")) || (s.equals("crt")) || (s.equals("cer")))) {
                System.out.println("输入错误！");
                System.exit(-1);
        }*/
        X509Certificate certificate  = PemToDer.getPemCert(pathSrc);
        PemToDer.writeDerCert(pathDst,certificate);
    }

}